package com.jiayou.common

import com.jiayou.autoconfiguration.AuthProperties
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.web.servlet.ConditionalOnMissingFilterBean
import org.springframework.core.Ordered
import org.springframework.stereotype.Component
import org.springframework.util.AntPathMatcher
import java.util.*
import javax.servlet.*
import javax.servlet.annotation.WebFilter
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
@author lishuang
@data   2021-04-02  11:48:04
@info   鉴权header，保证请求是网关转发而来
 */

class AuthFilter(private val authHandler: AuthHandler,
                 private val authProperties: AuthProperties) : Filter, Ordered {

    companion object {
        @JvmStatic
        private val antPathMatcher: AntPathMatcher = AntPathMatcher()

        @JvmStatic
        private val logger: Logger = LoggerFactory.getLogger(AuthFilter::class.java)
    }


    override fun init(p0: FilterConfig?) = logger.info("全局鉴权过滤器已初始化！")

    override fun doFilter(p0: ServletRequest, p1: ServletResponse, p2: FilterChain) {
        val httpServletRequest = p0 as HttpServletRequest
        //判断是否拦截该请求
        if (!assertInterceptor(p0)) {
            p2.doFilter(p0, p1)
            return
        }
        //判断是否带有权限特征
        if (httpServletRequest.getHeader(authProperties.code) != null) {
            //权限判断
            if (authHandler.doAuth(httpServletRequest.getHeader(authProperties.code))) {
                p2.doFilter(p0, p1)
                return
            }
        }
        Constant.accessDenied("非法越权访问！", p1 as HttpServletResponse)
        logger.error("非法越权访问！")
    }

    //判断是否拦截该请求
    private fun assertInterceptor(req: HttpServletRequest): Boolean {
        val requestURL = req.requestURI
        authProperties.filterPath.forEach {
            if (antPathMatcher.match(it, requestURL)) {
                return true
            }
        }
        return false
    }


    override fun destroy() = logger.info("全局鉴权过滤器已被销毁！")
    override fun getOrder() = -999
}